package fausto.cycles 
{
	import com.greensock.TweenMax;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	/**
	 * ...
	 * @author Ben.
	 */
	public class CyclesThumb extends Sprite
	{
		private var ml:Loader;
		
		private var ww:int = 120;
		private var hh:int = 120;
		
		public var _noThumb:Sprite
		public var _id:int
		
		public function CyclesThumb(_d:XML, _i:int):void 
		{
			_id = _i;
			buttonMode = true;
			mouseChildren = false;
			
			_noThumb.visible = false;
			
			ml = new Loader();
			ml.contentLoaderInfo.addEventListener(Event.INIT, onMediaReady);
			ml.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onMediaError);
			var lc:LoaderContext = new LoaderContext(true);
			
			ml.load(new URLRequest("img/" + _d.thumb), lc);
			
			addEventListener(MouseEvent.CLICK, onClick);
		}
		
		private function onClick(e:MouseEvent):void 
		{
			// GO TO FULL
			dispatchEvent(new Event("CYCLES_THUMB_FULL", true));
		}
		
		private function onMediaError(e:Event):void 
		{
			dispatchEvent(new Event("THUMB_LOADED", true));
			_noThumb.visible = true;
		}
		
		private function onMediaReady(e:Event):void 
		{
			ml.contentLoaderInfo.removeEventListener(Event.INIT, onMediaReady);
			
			var bd:BitmapData = new BitmapData(ml.width, ml.height);
			bd.draw(ml, null, null, null, null, true);
			var bmp:Bitmap = new Bitmap(bd, "auto", true);
			
			// RESIZE BMP
			var ri:Number = bmp.width / bmp.height;
			var rc:Number = ww / hh;
			
			if (rc <= ri)
			{
				bmp.width = ww;
				bmp.height = bmp.width / ri;
			}
			if (rc > ri)
			{
				bmp.height = hh;
				bmp.width = bmp.height * ri;
			}
			
			bmp.x = 20+(ww - bmp.width) / 2;
			bmp.y = 20+(hh - bmp.height) / 2;
			
			bmp.alpha = 0;
			
			TweenMax.to(bmp, 0.7, {alpha:1 } );
			
			addChild(bmp);
									
			dispatchEvent(new Event("THUMB_LOADED", true));
		}
		
	}

}